import axios from 'axios'

// 微信配置
const WX_CONFIG = {
  appid: 41531351523,
  redirectUri: encodeURIComponent(window.location.href)
}

// 静默授权获取OpenID
export const getWechatOpenId = async () => {
  const code = getUrlParam('code')
  console.log(code);
  
  
  if (!code) {
    // 触发微信授权跳转
    // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WX_CONFIG.appid}&redirect_uri=${WX_CONFIG.redirectUri}&response_type=code&scope=snsapi_base&state=wx_auth#wechat_redirect`
  } else {
    // 发送code到后端换取OpenID 
    try {
      const { data } = await axios.post('/api/auth/openid', { code })
      localStorage.setItem('wx_openid', data.openid)
      return data.openid
    } catch (error) {
      console.error('获取OpenID失败:', error)
      localStorage.removeItem('wx_openid')
    }
  }
}

// 获取URL参数
const getUrlParam = (name) => {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`)
  const r = window.location.search.substr(1).match(reg)
  return r ? decodeURIComponent(r[2]) : null
}